<?php

/**
 * Static content controller.
 *
 * This file will render views from views/pages/
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
App::uses('AppController', 'Controller');

/**
 * Static content controller
 *
 * Override this controller by placing a copy in controllers directory of an application
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers/pages-controller.html
 */
class PagesController extends AppController {

    /**
     * This controller does not use a model
     *
     * @var array
     */
    public $uses = array();

    /**
     * Displays a view
     *
     * @param mixed What page to display
     * @return void
     * @throws NotFoundException When the view file could not be found
     * 	or MissingViewException in debug mode.
     */
    public function display() {
        $path = func_get_args();

        $count = count($path);
        if (!$count) {
            return $this->redirect('/');
        }
        $page = $subpage = $title_for_layout = null;

        if (!empty($path[0])) {
            $page = $path[0];
        }
        if (!empty($path[1])) {
            $subpage = $path[1];
        }
        if (!empty($path[$count - 1])) {
            $title_for_layout = Inflector::humanize($path[$count - 1]);
        }
        $this->set(compact('page', 'subpage', 'title_for_layout'));

        try {
            $this->render(implode('/', $path));
        } catch (MissingViewException $e) {
            if (Configure::read('debug')) {
                throw $e;
            }
            throw new NotFoundException();
        }
    }

    public function admin_index() {
        $this->layout = 'backend/admin';
    }

    public function detail($id) {
        if (!empty($id)) {
            $this->loadModel('BenhHai');
            $benhhai = $this->BenhHai->find('first', array('conditions' => array(
                    'BenhHai.id' => $id)));
            $this->set(compact('benhhai'));
        }
    }

    public function index() {
       $title_for_layout="Shop thời trang nam nữ" ;
       $this->loadModel('TypeProduct');
       
       $types = $this->TypeProduct->find('list',array('conditions'=>array('TypeProduct.parent_id'=>''),'fields'=>array('id','type_name')));
       $this->set(compact('types','title_for_layout'));
    }
    public function getProduct($typeId)
    {
        $this->loadModel('Product');
        $typeId =  explode(",", $typeId);
        if(count($typeId)>1){
              $products = $this->Product->find('all',array('conditions'=>array('Product.type_product_id IN'=>$typeId),'recursive'=>-1));
       
        }
        else{
              $products = $this->Product->find('all',array('conditions'=>array('Product.type_product_id '=>$typeId[0]),'recursive'=>-1));
   
        }
       return $products;
        
    }
    public function getType($parentId)
    {
       $this->loadModel('TypeProduct');
       
       $types = $this->TypeProduct->find('list',array('conditions'=>array('TypeProduct.parent_id'=>$parentId),'fields'=>array('id','type_name')));
       return $types;
    }
     public function getTypeParent($type_fashion=null) {
       $this->loadModel('TypeProduct');
       if($type_fashion != '')
       {
           $types = $this->TypeProduct->find('list',array('conditions'=>array('TypeProduct.parent_id'=>'','type_fashion'=>$type_fashion),'fields'=>array('id','type_name')));
       }
       else{
            $types = $this->TypeProduct->find('list',array('conditions'=>array('TypeProduct.parent_id'=>''),'fields'=>array('id','type_name')));
      
       }
       return $types;
    }
    public function getProductTypeFashion($typeId,$type=null)
    {
        $this->loadModel('Product');
        $typeId =  explode(",", $typeId);
        if(count($typeId)>1){
              $products = $this->Product->find('all',array('conditions'=>array('Product.type_product_id IN'=>$typeId,'Product.type_fashion'=>$type),'recursive'=>-1));
       
        }
        else{
              $products = $this->Product->find('all',array('conditions'=>array('Product.type_product_id '=>$typeId[0],'Product.type_fashion'=>$type),'recursive'=>-1));
   
        }
       return $products;
        
    }
    public function getTypeDetail($id)
    {
        $this->loadModel('TypeProduct');

        $types = $this->TypeProduct->find('first',array('conditions'=>array('TypeProduct.id'=>$id),'fields'=>array('id','type_name')));
        return $types;
    }
    public function intro()
    {
        $title_for_layout="Giới thiệu- Shop thời trang nam nữ";
        $this->loadModel('Introduction');
        $intro = $this->Introduction->find('first');
        $this->set(compact('intro','title_for_layout'));
    }
    public function contact()
    {
        $title_for_layout="Liên hệ- shop thời trang nam nữ";
        $this->set(compact('title_for_layout'));
        if ($this->request->is('post') && !empty($this->request->data)) {
            $mailFrom = $this->request->data['email'];
            $fromName=  $this->request->data['fullname'];
            $phoneContact = $this->request->data['phone'];
            $content = $this->request->data['content'];
            $titleMail =" Tin liên hệ của khách hàng";
            $bodyContent =" Khách hàng ".$fromName." có địa chỉ email: ".$mailFrom;
            $bodyContent .= (!empty($phoneContact))?" và số điện thoại: ".$phoneContact:'';
            $bodyContent .=" đã liên hệ với royshop với nội dung như sau: \n".$content;
            App::uses('CakeEmail', 'Network/Email');
            $mailContack = new CakeEmail();
            $mailContack->from(array($mailFrom => $fromName));
            $mailContack->to('admin@royshop.vn');
            $mailContack->subject($titleMail);
            //$mailContack->send($bodyContent);
            //FunctionCommon::sendMail('admin@royshop.vn', $titleMail, $bodyContent, $mailFrom);
            //mail("admin@royshop.vn",$titleMail,$bodyContent,"From: $mailFrom\n");
			
			
            $message =" Email liên hệ đã được gởi";
            
            $this->request->data=array();
            $this->set(compact('message'));
            
        }
    }
    public function order($productId=null)
    {
        $title_for_layout="Đặt hàng online";
		$size =array('1'=>'Tùy chọn','2'=>'S','3'=>'M','4'=>'X','5'=>'XL');
        $order = array();
        $products= array();
        $number=1;
        $sSize=1;
        if(isset($this->request->data['product_id']))
        {
            $productId=$this->request->data['product_id'];
            $sSize=$this->request->data['size'];
            $number=$this->request->data['number'];
        }
        if($this->Session->check('order'))
        {
            $order=$this->Session->read('order');
        }
        $this->loadModel('Product');
        $product = $this->Product->find('first',array('conditions'=>array('Product.id'=>$productId)));
        if(!empty($product))
        {
            $order[$product['Product']['id']]=array('price'=>$product['Product']['price'],'number'=>$number,'size'=>$sSize);
        }
        if(!empty($order))
        {
            $products=$this->Product->find('all',array('conditions'=>array('Product.id'=>  array_keys($order))));
        }
        $this->Session->write('order',$order);
        $this->set(compact('order','products','size','title_for_layout'));
    }
    public function deleteOrder($productId)
    {
        if($this->Session->check('order'))
        {
            $order=$this->Session->read('order');
            unset($order[$productId]);
            $this->Session->write('order',$order);
        }
        $this->redirect("/pages/order");
    }
    public function confirm()
    {
        $title_for_layout="Đặt hàng online";
		$size =array('1'=>'Tùy chọn','2'=>'S','3'=>'M','4'=>'X','5'=>'XL');
        $order=array();
        $products=array();
        $this->loadModel('Product');
        if($this->Session->check('order'))
        {
            $order=$this->Session->read('order');
        }
        if(!empty($order))
        {
            $products=$this->Product->find('all',array('conditions'=>array('Product.id'=>  array_keys($order))));
        }
        $this->set(compact('products','order','size','title_for_layout'));
    }
    public function complete()
    {
        $title_for_layout=" Hoàn thành đặt hàng";
		$order=array();
        $result=true;
        $size =array('1'=>'Tùy chọn','2'=>'S','3'=>'M','4'=>'X','5'=>'XL');
        if ($this->request->is('post') && !empty($this->request->data) && $this->Session->check('order')) {
            $order= $this->Session->read('order');
            $data=$this->request->data;
            $contentOrder='';
        if(!empty($data) && !empty($order))
        {
            $this->loadModel('Custumer');
            if($data['id']!="")
            {
                $this->Custumer->set('id',$data['id']);
            }
            $this->Custumer->set('name',$data['fullname']);
            $this->Custumer->set('phone',$data['phone']);
            $this->Custumer->set('email',$data['email']);
            $this->Custumer->set('address',$data['address']);
            if($this->Custumer->save())
            {
                $id=$this->Custumer->id;
                $this->loadModel('Order');
                $i=0;
                foreach($order as $kOrder=>$vOrder)
                {
                    $i++;
                    $this->loadModel('Product');
                    $products = $this->Product->find('first',array('Product.id'=>$kOrder));
                    if(!empty($products))
                    {
                        $contentOrder .="\nSản phẩm số  :".$i;
                        $contentOrder .="\n- Tên sản phẩm: ".$products['Product']['product_name'];
                        $contentOrder .="\n- Mã sản phẩm: ".$products['Product']['product_code'];
                        $contentOrder .="\n- Loại sản phẩm: ".$products['TypeProduct']['type_name'];
                        $contentOrder .="\n- Size: ".$size[$vOrder['size']];
                        $contentOrder .="\n- Số lượng: ".$vOrder['number'];
                        $contentOrder .="\n================================";
                    }
                    $this->Order->set('product_id',$kOrder);
                    $this->Order->set('custumer_id',$id);
                    $this->Order->set('product_size',$vOrder['size']);
                    $this->Order->set('number',$vOrder['number']);
                    $this->Order->set('price',$vOrder['price']);
                    $this->Order->set('order_date',date("y-m-d H:s:i"));
                    if(!$this->Order->save())
                    {
                        $result=false;
                        break;
                    }
                }
            }
            $this->Session->delete('order');
            if($result)
            {
              $contentClient="Royshop đã nhận được đơn đặt hàng của bạn\n. Cám ơn bạn đã đặt hàng tại cửa hàng chúng tôi, chúng tôi sẽ liên lạc với bạn trong thời gian sớm nhất.\n Xin chân thành cám ơn";
              $titleClien = "Email xác nhận đặt hàng";
              $titleServer = "Thông báo đã nhận được đơn đặt hàng";
              $contentServer =" Hệ thống đã nhận được đơn đạt hàng từ địa chỉ email: ".$data['email']. " vào lúc ".date("d-m-y h:s:i");
              $contentServer .="\n Thông tin đặt hàng như sau:";
              $contentServer .= $contentOrder;
              App::uses('CakeEmail', 'Network/Email');
              $mailClient = new CakeEmail('gmail');
              $mailClient->from(array(ADMIN_MAIL => 'admin'));
              $mailClient->to($data['email']);
              $mailClient->subject($titleClien);
              //$mailClient->send($contentClient);
              
              $mailAdmin = new CakeEmail('gmail');
              $mailAdmin->from(array(RS_MAIL => 'admin'));
              $mailAdmin->to(ADMIN_MAIL);
              $mailAdmin->subject($titleServer);
              //$mailAdmin->send($contentServer);
              $message=" RoyShop xin cám ơn bạn đã đặt hàng tại cửa hàng chúng tôi, chúng tôi sẽ liên lạc lại với bạn trong thời gian sớm nhất, xin cám ơn." ; 
            }
            else{
                $message = "Xin lỗi bạn, đã có lỗi trong quá trình đặt hàng";
            }
            $this->set(compact('message','title_for_layout'));
            
        }
		
    }
		$this->set(compact('title_for_layout'));
    }
    public function checkEmail()
    {
        $this->autoRender=false;
        $this->layout=false;
        $data=$this->request->data;
        if(!empty($data))
        {
            $email = $data['email'];
            $this->loadModel('Custumer');
            $custumer = $this->Custumer->find('first',array('conditions'=>array('Custumer.email'=>$email)));
            if(!empty($custumer))
            {
                return json_encode($custumer['Custumer']);
                
            }
            else return false;
        }
    }
    
            

}
